package com.webflux.test.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import java.util.stream.Stream;

@Slf4j
@RestController
public class WebFluxController {

    // 普通的SpringMVC方法
    @GetMapping("/web/mvc")
    private String webMvc() {
        log.info("webMvc start");
        String result = createStr();
        log.info("webMvc end.");
        return result;
    }

    // WebFlux(返回的是Mono)
    @GetMapping("/web/flux")
    private Mono<String> webFlux() {
        log.info("webFlux start");
        Mono<String> result = Mono.fromSupplier(() -> createStr());
        log.info("webFlux end.");
        return result;
    }

    // WebFlux(返回的是flux)
    @GetMapping(value = "/web/flux/03",  produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    private Flux<String> webFlux03() {
        return Flux.fromStream(IntStream.range(1,10).mapToObj(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "flux data --" + i;
        }));


    }

    // 阻塞5秒钟
    private String createStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
        }
        return "some string";
    }

    public static void main(String[] args) {

        /*Flux.generate(()-> 1, (i,  sink)->{
            sink.next(i);
            if(i == 5){
                sink.complete();
            }
            return  ++i;
        }).subscribe(System.out::println);*/

        /*Flux.create(sink -> {
            for(int i = 1; i<= 5; i++ ){
                sink.next(i);
            }
        }).subscribe(System.out::println);*/

        /*Mono.create(sink -> sink.success("zhangsan")).subscribe(System.out::println);*/
       /* Mono.just("zhangsan")
                .concatWith(Mono.error(new RuntimeException("数据错误")))
                .onErrorReturn("runtime error")
                .subscribe(System.out::println, System.err::println)
                ;*/

       /*Flux.just("zhangsan", "lisi", "wangwu")
               .concatWith(Mono.error(new RuntimeException("请求异常了")))
               *//*.onErrorReturn("runtime error")*//*
               .subscribe(data -> System.out.println(data), err -> System.out.println(err), () -> System.out.println("complete"));*/

    }
}
